<template>
  <PageContainer :title="pageTitle" :description="pageDescription">
    <template #header-actions>
      <el-button @click="goBack" :icon="Back">返回楼栋列表</el-button>
    </template>

    <div class="layout-toolbar">
      <el-space wrap>
        <el-input v-model="searchKeyword" placeholder="按房号搜索 (支持模糊)" clearable style="width: 220px" @input="handleSearch">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <!-- 选择模式多选框 -->
        <el-checkbox-group v-model="selectionMode" @change="handleSelectionModeChange">
          <el-checkbox value="vertical">选竖排</el-checkbox>
          <el-checkbox value="horizontal">选一层</el-checkbox>
        </el-checkbox-group>

        <!-- 选择状态显示 -->
        <el-tag v-if="selectedHouseholds.length > 0" type="info" size="small">
          已选择 {{ selectedHouseholds.length }} 个房户
        </el-tag>

        <!-- 清空选择按钮 -->
        <el-button 
          :disabled="selectedHouseholds.length === 0"
          @click="handleClearSelection"
        >
          清空选择
        </el-button>

        <!-- 配置户型按钮 -->
        <el-button 
          type="primary" 
          :disabled="selectedHouseholds.length === 0"
          @click="handleConfigureHouseType"
        >
          配置户型 ({{ selectedHouseholds.length }})
        </el-button>

        <el-space class="legend" :size="8">
          <span class="legend-item"><i class="dot dot-enabled" /> 启用</span>
          <span class="legend-item"><i class="dot dot-disabled" /> 禁用</span>
        </el-space>
      </el-space>
    </div>

    <el-skeleton v-if="loading" animated :rows="6" />

    <div v-else class="building-layout">
      <el-empty v-if="!floorsSorted.length" description="暂无布局数据" />

      <template v-else>
        <div class="units-container">
          <div v-for="unit in unitsGrouped" :key="unit.id" class="unit-wrapper">
            <el-card shadow="hover" class="unit-card">
              <template #header>
                <div class="unit-card-header">
                  <div class="title">
                    <el-icon><OfficeBuilding /></el-icon>
                    <span class="unit-name">{{ unit.unitName }}</span>
                  </div>
                  <el-tag size="small" type="info">{{ getUnitFilteredCount(unit) }}/{{ getUnitTotalCount(unit) }}</el-tag>
                </div>
              </template>

              <div class="unit-floor" v-for="floor in unit.floors" :key="floor.floorNumber">
                <el-divider content-position="left">{{ floor.floorNumber }} 层</el-divider>
                <div class="household-container">
                  <div class="household-row">
                    <SmartTooltip v-for="house in filterHouseholds(floor.households)" :key="house.id" :show-after="300" placement="top">
                      <template #content>
                        <div>
                          <div>房号：{{ house.roomNumber || '-' }}</div>
                          <div>编码：{{ house.householdCode || '-' }}</div>
                          <div>楼层：{{ house.floorNumber ?? '-' }}</div>
                          <div>面积：{{ house.area ?? '-' }}㎡（可用：{{ house.usableArea ?? '-' }}㎡）</div>
                          <div>户型：{{ house.roomType ?? '-' }}</div>
                          <div>朝向：{{ house.orientation || '-' }}</div>
                          <div>产权：{{ house.propertyType ?? '-' }}</div>
                          <div>业主：{{ house.ownerName || '-' }}（{{ house.ownerPhone || '-' }}）</div>
                        </div>
                      </template>
                      <div 
                        class="household-item" 
                        :class="[getHouseholdClass(house), { 'selected': isHouseholdSelected(house) }]"
                        @click="(event) => handleHouseholdClick(house, event)"
                      >
                        <div class="household-content">
                          <el-checkbox 
                            :model-value="isHouseholdSelected(house)"
                            @change="(checked: boolean) => handleHouseholdCheckboxChange(house, checked)"
                            @click.stop
                          />
                          <div class="room">{{ house.roomNumber }}</div>
                          <el-tag size="small" :type="house.status === STATUS.ENABLED ? 'success' : 'danger'">
                            {{ house.status === STATUS.ENABLED ? '启用' : '禁用' }}
                          </el-tag>
                        </div>
                      </div>
                    </SmartTooltip>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </template>
    </div>

    <!-- 配置户型对话框 -->
    <el-dialog 
      v-model="houseTypeDialogVisible" 
      title="配置户型" 
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="house-type-dialog">
        <div class="selected-info">
          <el-alert 
            :title="`已选择 ${selectedHouseholds.length} 个房户`"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
        
        <el-form :model="houseTypeForm" label-width="100px">
          <el-form-item label="选择户型" required>
            <el-select 
              v-model="houseTypeForm.houseTypeId" 
              placeholder="请选择户型"
              style="width: 100%"
              :loading="houseTypeLoading"
            >
              <el-option 
                v-for="houseType in houseTypeList" 
                :key="houseType.id"
                :label="houseType.houseTypeName"
                :value="houseType.id"
              >
                <div class="house-type-option">
                  <div class="house-type-name">{{ houseType.houseTypeName }}</div>
                  <div class="house-type-desc">
                    {{ houseType.totalArea }}㎡ | {{ houseType.bedroomCount }}室{{ houseType.livingRoomCount }}厅
                  </div>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <el-button @click="houseTypeDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirmHouseType"
          :loading="houseTypeSubmitting"
          :disabled="!houseTypeForm.houseTypeId"
        >
          确认配置
        </el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Back, OfficeBuilding, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '@/components/PageContainer.vue'
import { buildingApi, type BuildingLayoutData, type FloorData, type UnitData, type HouseholdData as BaseHouseholdData } from '@/api/building'
import { householdApi } from '@/api/household'
import { houseTypeApi } from '@/api/region/houseType'
import { propertyCompanyApi } from '@/api/property/propertyCompany'
import SmartTooltip from '@/components/SmartTooltip.vue'
import { STATUS } from '@/constants/enums'

const route = useRoute()
const router = useRouter()

const buildingId = computed(() => Number(route.params.id))
const loading = ref<boolean>(false)
const layoutData = ref<BuildingLayoutData | null>(null)
const searchKeyword = ref<string>('')

// 选择相关状态
const selectionMode = ref<string[]>([])
const selectedHouseholds = ref<HouseholdData[]>([])

// 户型配置相关状态
const houseTypeDialogVisible = ref<boolean>(false)
const houseTypeLoading = ref<boolean>(false)
const houseTypeSubmitting = ref<boolean>(false)
const houseTypeList = ref<any[]>([])
const houseTypeForm = ref({
  houseTypeId: undefined as number | undefined
})

const pageTitle = computed(() => layoutData.value?.buildingName ? `${layoutData.value.buildingName} - 楼栋布局` : '楼栋布局')
const pageDescription = computed(() => layoutData.value?.buildingName ? `查看 ${layoutData.value.buildingName} 的楼层与单元房户分布` : '楼层与单元房户分布')

// 所有楼层，按楼层号倒序（最高层在前）
const floorsSorted = computed<FloorData[]>(() => {
  const floors = layoutData.value?.floors || []
  return floors.slice().sort((a, b) => b.floorNumber - a.floorNumber)
})

type HouseholdData = BaseHouseholdData & {
  householdCode?: string
  buildingId?: number
  unitId?: number
  floorNumber?: number
  usableArea?: number
  roomType?: number
  orientation?: string
  propertyType?: number
  ownerName?: string
  ownerPhone?: string
}

type UnitGroup = {
  id: number
  unitName: string
  floors: { floorNumber: number; households: HouseholdData[] }[]
}

// 按单元分组，每个单元下包含所有楼层（倒序）
const unitsGrouped = computed<UnitGroup[]>(() => {
  const groupedMap = new Map<number, UnitGroup>()
  for (const floor of floorsSorted.value) {
    for (const unit of (floor.units || [])) {
      const key = unit.id
      if (!groupedMap.has(key)) {
        groupedMap.set(key, { id: unit.id, unitName: unit.unitName, floors: [] })
      }
      groupedMap.get(key)!.floors.push({ floorNumber: floor.floorNumber, households: unit.households || [] })
    }
  }
  // 单元按名称排序，楼层已倒序
  return Array.from(groupedMap.values()).sort((a, b) => String(a.unitName).localeCompare(String(b.unitName)))
})

const handleSearch = () => {
  // 文本变化即触发计算属性过滤
}

const filterHouseholds = (list: HouseholdData[]): HouseholdData[] => {
  const data = Array.isArray(list) ? list : []
  if (!searchKeyword.value) return data
  const kw = searchKeyword.value.trim()
  console.log('搜索过滤 - 关键词:', kw, '原始数据量:', data.length)
  const filtered = data.filter(h => String(h.roomNumber || '').includes(kw))
  console.log('搜索过滤 - 过滤后数据量:', filtered.length)
  return filtered
}

const getUnitFilteredCount = (unit: UnitGroup): number => {
  return unit.floors.reduce((sum, f) => sum + filterHouseholds(f.households).length, 0)
}

const getUnitTotalCount = (unit: UnitGroup): number => {
  return unit.floors.reduce((sum, f) => sum + (Array.isArray(f.households) ? f.households.length : 0), 0)
}

const getHouseholdClass = (house: HouseholdData) => {
  return house.status === STATUS.ENABLED ? 'enabled' : 'disabled'
}

// 检查房户是否被选中
const isHouseholdSelected = (house: HouseholdData): boolean => {
  return selectedHouseholds.value.some(h => h.id === house.id)
}

// 处理房户点击事件
const handleHouseholdClick = (house: HouseholdData, event?: MouseEvent) => {
  if (selectionMode.value.length === 0) {
    // 如果没有选择模式，直接切换选中状态
    toggleHouseholdSelection(house)
  } else {
    // 如果有选择模式，根据模式进行批量选择
    handleBatchSelection(house, event)
  }
}

// 处理房户复选框变化
const handleHouseholdCheckboxChange = (house: HouseholdData, checked: boolean) => {
  if (checked) {
    addHouseholdToSelection(house)
  } else {
    removeHouseholdFromSelection(house)
  }
}

// 切换房户选中状态
const toggleHouseholdSelection = (house: HouseholdData) => {
  const index = selectedHouseholds.value.findIndex(h => h.id === house.id)
  if (index > -1) {
    selectedHouseholds.value.splice(index, 1)
  } else {
    selectedHouseholds.value.push(house)
  }
}

// 添加房户到选中列表
const addHouseholdToSelection = (house: HouseholdData) => {
  if (!isHouseholdSelected(house)) {
    selectedHouseholds.value.push(house)
  }
}

// 从选中列表移除房户
const removeHouseholdFromSelection = (house: HouseholdData) => {
  const index = selectedHouseholds.value.findIndex(h => h.id === house.id)
  if (index > -1) {
    selectedHouseholds.value.splice(index, 1)
  }
}

// 处理批量选择
const handleBatchSelection = (clickedHouse: HouseholdData, event?: MouseEvent) => {
  // 检查是否按住Ctrl键进行多选
  const isMultiSelect = event?.ctrlKey || event?.metaKey
  
  // 获取当前点击的房户信息
  const targetUnitId = clickedHouse.unitId
  const targetRoomNumber = clickedHouse.roomNumber
  const targetFloorNumber = clickedHouse.floorNumber
  
  // 确定要选择的房户列表
  let householdsToSelect: HouseholdData[] = []
  
  if (selectionMode.value.includes('vertical')) {
    // 选竖排：选择同一单元内相同房号的房户
    console.log('选竖排模式，目标单元ID:', targetUnitId, '目标房号:', targetRoomNumber)
    console.log('当前搜索关键词:', searchKeyword.value)
    console.log('所有单元列表:', unitsGrouped.value.map(u => ({ id: u.id, name: u.unitName })))
    
    for (const unit of unitsGrouped.value) {
      if (unit.id === targetUnitId) {
        console.log('找到目标单元:', unit.unitName)
        for (const floor of unit.floors) {
          console.log('检查楼层:', floor.floorNumber, '房户数量:', floor.households.length)
          console.log('原始房户列表:', floor.households.map(h => h.roomNumber))
          
          // 使用与显示相同的过滤逻辑
          const filteredHouseholds = filterHouseholds(floor.households)
          console.log('过滤后房户数量:', filteredHouseholds.length)
          console.log('过滤后房户列表:', filteredHouseholds.map(h => h.roomNumber))
          
          for (const house of filteredHouseholds) {
            // 提取房号（去掉楼层号）
            const houseRoomNumber = String(house.roomNumber || '')
            const targetRoomNumberStr = String(targetRoomNumber || '')
            
            // 提取房号的后两位数字（去掉楼层号）
            const houseRoomSuffix = houseRoomNumber.slice(-2) // 取后两位
            const targetRoomSuffix = targetRoomNumberStr.slice(-2) // 取后两位
            
            console.log('检查房户:', house.roomNumber, '房号后缀:', houseRoomSuffix, '目标房号后缀:', targetRoomSuffix)
            console.log('房号比较:', houseRoomSuffix, '===', targetRoomSuffix, '结果:', houseRoomSuffix === targetRoomSuffix)
            
            if (houseRoomSuffix === targetRoomSuffix) {
              householdsToSelect.push(house)
              console.log('添加房户到选择列表:', house.roomNumber)
            }
          }
        }
      }
    }
    
    console.log('最终选择列表:', householdsToSelect.map(h => h.roomNumber))
  }
  
  if (selectionMode.value.includes('horizontal')) {
    // 选一层：选择同一单元内同一层的房户
    console.log('选一层模式，目标单元ID:', targetUnitId, '目标楼层:', targetFloorNumber)
    
    for (const unit of unitsGrouped.value) {
      if (unit.id === targetUnitId) {
        console.log('找到目标单元:', unit.unitName)
        for (const floor of unit.floors) {
          console.log('检查楼层:', floor.floorNumber, '是否匹配:', floor.floorNumber === targetFloorNumber)
          if (floor.floorNumber === targetFloorNumber) {
            console.log('找到目标楼层，房户数量:', floor.households.length)
            // 使用与显示相同的过滤逻辑
            const filteredHouseholds = filterHouseholds(floor.households)
            console.log('过滤后房户数量:', filteredHouseholds.length)
            
            for (const house of filteredHouseholds) {
              householdsToSelect.push(house)
              console.log('添加房户到选择列表:', house.roomNumber)
            }
          }
        }
      }
    }
    
    console.log('最终选择列表:', householdsToSelect.map(h => h.roomNumber))
  }
  
  // 处理选择逻辑
  if (isMultiSelect) {
    // 多选模式：累加到当前选择
    for (const house of householdsToSelect) {
      addHouseholdToSelection(house)
    }
  } else {
    // 单选模式：智能替换当前选择
    if (selectionMode.value.includes('vertical')) {
      // 选竖排：移除同一单元内相同房号的房户，然后添加新的竖排
      const targetRoomSuffix = String(targetRoomNumber || '').slice(-2)
      selectedHouseholds.value = selectedHouseholds.value.filter(house => {
        const houseRoomSuffix = String(house.roomNumber || '').slice(-2)
        return !(house.unitId === targetUnitId && houseRoomSuffix === targetRoomSuffix)
      })
      // 添加新的竖排选择
      for (const house of householdsToSelect) {
        addHouseholdToSelection(house)
      }
    } else if (selectionMode.value.includes('horizontal')) {
      // 选一层：移除同一单元内同一层的房户，然后添加新的一层
      selectedHouseholds.value = selectedHouseholds.value.filter(house => 
        !(house.unitId === targetUnitId && house.floorNumber === targetFloorNumber)
      )
      // 添加新的一层选择
      for (const house of householdsToSelect) {
        addHouseholdToSelection(house)
      }
    } else {
      // 如果没有选择模式，直接替换所有选择
      selectedHouseholds.value = []
      for (const house of householdsToSelect) {
        addHouseholdToSelection(house)
      }
    }
  }
  
  // 显示选择结果提示
  if (selectedHouseholds.value.length === 0) {
    ElMessage.info('未找到符合条件的房户')
  } else {
    // 显示选择结果
    const modeText = selectionMode.value.includes('vertical') ? '竖排' : 
                    selectionMode.value.includes('horizontal') ? '一层' : '房户'
    const unitName = unitsGrouped.value.find(u => u.id === targetUnitId)?.unitName || ''
    const targetText = selectionMode.value.includes('vertical') ? `房号${targetRoomNumber}` :
                      selectionMode.value.includes('horizontal') ? `${targetFloorNumber}层` : ''
    
    if (householdsToSelect.length > 0) {
      ElMessage.success(`已选择${unitName}${targetText}的${householdsToSelect.length}个${modeText}房户`)
    }
  }
}

// 处理选择模式变化
const handleSelectionModeChange = () => {
  // 当选择模式发生变化时，不清空选择，让用户手动管理
  // 这样可以避免取消勾选模式时意外清空已选择的房户
}

// 处理清空选择
const handleClearSelection = () => {
  selectedHouseholds.value = []
  ElMessage.info('已清空所有选择')
}

// 处理配置户型
const handleConfigureHouseType = async () => {
  if (selectedHouseholds.value.length === 0) {
    ElMessage.warning('请先选择要配置的房户')
    return
  }
  
  try {
    await loadHouseTypeList()
    houseTypeDialogVisible.value = true
  } catch (error) {
    ElMessage.error('加载户型列表失败')
  }
}

// 加载户型列表
const loadHouseTypeList = async () => {
  if (!layoutData.value?.communityId) {
    throw new Error('无法获取社区信息')
  }
  
  houseTypeLoading.value = true
  try {
    // 根据社区ID获取物业公司ID，再获取户型列表
    const propertyCompanyResponse = await propertyCompanyApi.getPropertyCompanyIdByCommunityId(layoutData.value.communityId)
    if (propertyCompanyResponse.code !== 200 || !propertyCompanyResponse.data) {
      throw new Error('社区未关联物业公司')
    }
    
    const propertyCompanyId = propertyCompanyResponse.data
    
    // 根据物业公司ID获取户型列表（使用区域管理模块的API）
    const response = await houseTypeApi.getHouseTypesByPropertyCompany(propertyCompanyId)
    if (response.code === 200) {
      houseTypeList.value = response.data || []
    } else {
      throw new Error(response.message || '获取户型列表失败')
    }
  } finally {
    houseTypeLoading.value = false
  }
}

// 确认配置户型
const handleConfirmHouseType = async () => {
  if (!houseTypeForm.value.houseTypeId) {
    ElMessage.warning('请选择户型')
    return
  }
  
  try {
    houseTypeSubmitting.value = true
    
    const householdIds = selectedHouseholds.value.map(h => h.id)
    const response = await householdApi.batchUpdateHouseType(householdIds, houseTypeForm.value.houseTypeId)
    
    if (response.code === 200) {
      ElMessage.success('户型配置成功')
      houseTypeDialogVisible.value = false
      selectedHouseholds.value = []
      houseTypeForm.value.houseTypeId = undefined
      // 重新加载布局数据
      await loadLayout()
    } else {
      throw new Error(response.message || '配置户型失败')
    }
  } catch (error) {
    ElMessage.error('配置户型失败：' + (error as Error).message)
  } finally {
    houseTypeSubmitting.value = false
  }
}

const loadLayout = async () => {
  if (!buildingId.value || Number.isNaN(buildingId.value)) return
  loading.value = true
  try {
    const res = await buildingApi.getBuildingLayout(buildingId.value)
    layoutData.value = res.data || null
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.push('/region/building')
}

onMounted(() => {
  loadLayout()
})
</script>

<style scoped>
.layout-toolbar {
  margin-bottom: 16px;
}
.legend {
  margin-left: 8px;
  color: var(--el-text-color-secondary);
}
.legend-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}
.dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
}
.dot-enabled { background: #67C23A; }
.dot-disabled { background: #F56C6C; }

.building-layout {
  min-height: 200px;
}
.unit-card {
  margin-bottom: 16px;
}
.unit-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.unit-card-header .title {
  display: flex;
  align-items: center;
  gap: 8px;
}
.unit-name {
  font-weight: 600;
}
.units-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  width: 100%;
}

.unit-wrapper {
  flex: 0 0 auto;
  min-width: 300px;
}

.household-container {
  width: 100%;
}

.household-row {
  display: flex;
  flex-wrap: nowrap;
  gap: 8px;
  padding-bottom: 4px;
}
.household-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 10px;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  min-width: 120px;
  flex-shrink: 0;
  cursor: pointer;
  transition: all 0.2s;
}
.household-item.enabled {
  background: #f6ffed;
  border-color: #b7eb8f;
}
.household-item.disabled {
  background: #fff2f0;
  border-color: #ffccc7;
}
.household-item.selected {
  border-color: #409eff;
  background: #ecf5ff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
.household-item:hover {
  border-color: #409eff;
}
.household-content {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}
.household-item .room {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.house-type-dialog {
  padding: 16px 0;
}
.selected-info {
  margin-bottom: 16px;
}
.house-type-option {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.house-type-name {
  font-weight: 500;
}
.house-type-desc {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

@media (max-width: 768px) {
  .unit-wrapper {
    min-width: 280px;
  }
  .household-item {
    min-width: 100px;
  }
}
@media (max-width: 480px) {
  .unit-wrapper {
    min-width: 260px;
  }
  .household-item {
    min-width: 90px;
  }
}
</style>


